<?php

namespace App\Console\Commands\Cruise;

use App\Library\Rms\RmsShopApi;
use App\Models\Cruise\CruiseCheckAgainstModel;
use App\Models\Cruise\CruiseCheckDetailModel;
use App\Models\Cruise\CruiseCheckErrorModel;
use App\Models\Cruise\CruiseCheckRectifyModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;

class CruiseCheckChangeShopCommand extends Command
{
    protected $signature = 'cruise:cruise_check_change_shop {cruise_order_id} {target_shop_code}';

    protected $description = '稽核单变更门店';


    /**
     * Execute the console command.
     * @return int
     * @throws GuzzleException
     */
    public function handle()
    {
        $cruiseOrderId = $this->argument('cruise_order_id');
        $targetShopCode = $this->argument('target_shop_code');

        if (!$cruiseOrderId || !$targetShopCode) {
            $this->info("参数错误");
            die;
        }

        $cruiseOrder = CruiseOrderModel::query()->find($cruiseOrderId);
        if (!$cruiseOrder) {
            $this->info("稽核单不存在");
            die;
        }

        if ($cruiseOrder->type != CruiseOrderModel::TYPE_CHECK) {
            $this->info("仅支持type=3，夸父稽核");
            die;
        }

        $targetShopId = (new RmsShopApi)->getShopByCode($targetShopCode)['data']['id'] ?? 0;
        if (!$targetShopId) {
            $this->info("门店不存在");
            die;
        }

        $orderNo = OpenShopMainProcessModel::query()->where('shopId', $targetShopId)->value('orderNo');
        if (!$orderNo) {
            $this->info("门店未开店");
            die;
        }

        // cruise_order
        $cruiseOrder->shopId = $targetShopId;
        $cruiseOrder->orderNo = $orderNo;
        $cruiseOrder->save();

        // cruise_order_detail
        $cruiseOrderDetailId = CruiseCheckDetailModel::query()->where('orderId', $cruiseOrderId)->value('id');

        if ($cruiseOrderDetailId) {

            // cruise_check_errors
            $errorNum = CruiseCheckErrorModel::query()->where('cruiseCheckDetailId', $cruiseOrderDetailId)->update(['shopId' => $targetShopId]);
            $this->info("errorNum: $errorNum");

            // cruise_check_against
            $againstNum = CruiseCheckAgainstModel::query()->where('cruiseCheckDetailId', $cruiseOrderDetailId)->update(['shopId' => $targetShopId]);
            $this->info("againstNum: $againstNum");

            // cruise_check_rectify
            $rectifyNum = CruiseCheckRectifyModel::query()->where('cruiseCheckDetailId', $cruiseOrderDetailId)->update(['shopId' => $targetShopId]);
            $this->info("rectifyNum: $rectifyNum");
        }

    }
}
